<template>
  <div class="sidebar-container">
    <!-- 精选推荐模块 -->
    <div class="module card">
      <div class="module-header">
        <h2><el-icon><Star /></el-icon> 精选推荐</h2>
        <div class="tabs-container">
          <el-radio-group
              v-model="activeRecommendationTab"
              size="small"
          >
            <el-radio-button label="resources">资源</el-radio-button>
            <el-radio-button label="activities">活动</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <div class="module-body">
        <div v-if="activeRecommendationTab === 'resources'" class="recommendation-list">
          <div
              v-for="(item, index) in resourceRecommendations"
              :key="index"
              class="recommendation-item"
              @click="handleRecommendationClick(item)"
          >
            <div class="recommendation-icon">
              <el-icon><component :is="getIconComponent(item.icon)" /></el-icon>
            </div>
            <div class="recommendation-details">
              <div class="recommendation-title">{{ item.title }}</div>
              <div class="recommendation-description">{{ item.description }}</div>
            </div>
          </div>
        </div>

        <div v-else class="activity-list">
          <div
              v-for="(activity, index) in activityRecommendations"
              :key="index"
              class="activity-item"
              @click="handleActivityClick(activity)"
          >
            <div class="activity-icon">
              <el-icon><component :is="getIconComponent(activity.icon)" /></el-icon>
            </div>
            <div class="activity-details">
              <div class="activity-title">{{ activity.title }}</div>
              <div class="activity-time">{{ activity.time }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 新闻通知模块 -->
    <div class="module card">
      <div class="module-header">
        <h2><el-icon><Bell /></el-icon> 新闻通知</h2>
        <div class="tabs-container">
          <el-radio-group
              v-model="activeNewsTab"
              size="small"
          >
            <el-radio-button label="news">新闻</el-radio-button>
            <el-radio-button label="notices">通知</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <div class="module-body">
        <div v-if="activeNewsTab === 'news'" class="news-list">
          <div
              v-for="(news, index) in newsItems"
              :key="index"
              class="news-item"
              @click="handleNewsClick(news)"
          >
            <div class="news-badge" :class="news.type">{{ news.type === 'important' ? '重要' : '新闻' }}</div>
            <div class="news-content">
              <div class="news-title">{{ news.title }}</div>
              <div class="news-time">{{ news.time }}</div>
            </div>
          </div>
        </div>

        <div v-else class="notices-list">
          <div
              v-for="(notice, index) in notices"
              :key="index"
              class="notice-item"
              @click="handleNoticeClick(notice)"
          >
            <div class="notice-icon">
              <el-icon><BellFilled /></el-icon>
            </div>
            <div class="notice-content">
              <div class="notice-title">{{ notice.title }}</div>
              <div class="notice-time">{{ notice.time }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 我的日程模块 -->
    <div class="module card">
      <div class="module-header">
        <h2><el-icon><Calendar /></el-icon> 我的日程</h2>
        <div class="month-selector">
          <el-date-picker
              v-model="selectedMonth"
              type="month"
              placeholder="选择月份"
              format="YYYY年MM月"
              value-format="YYYY-MM"
              @change="changeMonth"
              class="custom-month-picker"
          />
        </div>
      </div>
      <div class="module-body">
        <div class="calendar-container">
          <div class="calendar-header">
            <div v-for="day in weekDays" :key="day" class="calendar-day-header">
              {{ day }}
            </div>
          </div>
          <div class="calendar-grid">
            <div
                v-for="(day, index) in calendarDays"
                :key="index"
                class="calendar-day"
                :class="{
                'current-month': day.isCurrentMonth,
                'today': day.isToday,
                'has-event': day.hasEvent
              }"
                @click="handleDayClick(day)"
            >
              <div class="day-number">{{ day.date.getDate() }}</div>
              <div v-if="day.hasEvent" class="event-indicator"></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 通知详情弹窗 -->
    <el-dialog
        v-model="noticeDetailVisible"
        :title="currentNotice?.title"
        width="60%"
        :before-close="handleCloseNoticeDetail"
    >
      <NoticeDetail
          v-if="currentNotice"
          :notice="currentNotice"
          tab-type="received"
          @close="noticeDetailVisible = false"
      />
    </el-dialog>

    <!-- 活动详情弹窗 -->
    <ActivityDetailDialog
        v-model:visible="activityDetailVisible"
        :activity-id="selectedActivityId"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getStudentSidebar, markNoticeAsRead } from '@/api/student';
import { ElMessage } from 'element-plus';
import NoticeDetail from './NoticeDetail.vue';
import ActivityDetailDialog from './ActivityDetailDialog.vue';
import {
  Star, Bell, Calendar, BellFilled,
  VideoPlay, Reading, DataBoard,
  Collection, User, School, Flag,
  Clock, ChatDotRound, Document,
  VideoCamera, Picture, Notebook, SetUp, ReadingLamp, MagicStick
} from '@element-plus/icons-vue';

const router = useRouter();

// 响应式数据
const activeRecommendationTab = ref('resources');
const activeNewsTab = ref('notices');
const selectedMonth = ref('');
const today = ref(new Date());
const weekDays = ['日', '一', '二', '三', '四', '五', '六'];

// 通知详情相关
const noticeDetailVisible = ref(false);
const currentNotice = ref(null);

// 活动详情相关
const activityDetailVisible = ref(false);
const selectedActivityId = ref(null);

// 数据
const resourceRecommendations = ref([]);
const activityRecommendations = ref([]);
const newsItems = ref([]);
const notices = ref([]);
const calendarDays = ref([]);

// 图标映射表 - 根据后台返回的icon字符串映射到实际组件
const iconMap = {
  // 资源相关图标
  'VideoPlay': VideoPlay,
  'VideoCamera': VideoCamera,
  'Reading': Reading,
  'ReadingLamp': ReadingLamp,
  'DataBoard': DataBoard,
  'Collection': Collection,
  'Document': Document,
  'Notebook': Notebook,
  'Picture': Picture,

  // 活动相关图标
  'User': User,
  'School': School,
  'Flag': Flag,
  'Clock': Clock,
  'ChatDotRound': ChatDotRound,
  'SetUp': SetUp,
  'MagicStick': MagicStick,

  // 默认图标
  'Star': Star,
  'Bell': Bell,
  'Calendar': Calendar,
  'BellFilled': BellFilled
};

// 根据图标名称获取对应的组件
const getIconComponent = (iconName) => {
  return iconMap[iconName] || Collection; // 默认使用 Collection 图标
};

// 从URL中提取ID的辅助函数
const extractIdFromUrl = (url) => {
  if (!url) return null;
  const match = url.match(/\/(\d+)$/);
  return match ? parseInt(match[1]) : null;
};

// 加载侧边栏数据
const loadSidebarData = async () => {
  try {
    // 从localStorage获取用户ID
    const userInfoStr = localStorage.getItem('userInfo');
    let userId = '';

    if (userInfoStr) {
      try {
        const userInfo = JSON.parse(userInfoStr);
        userId = userInfo.id || '';
      } catch (error) {
        console.error('解析用户信息失败', error);
      }
    }

    if (!userId) {
      ElMessage.error('无法获取用户信息，请重新登录');
      return;
    }

    const response = await getStudentSidebar(parseInt(userId));

    if (response.success) {
      const data = response.data;

      // 更新推荐数据
      if (data.recommendations) {
        resourceRecommendations.value = data.recommendations.resourceRecommendations || [];
        activityRecommendations.value = data.recommendations.activityRecommendations || [];
        activeRecommendationTab.value = data.recommendations.activeTab || 'resources';
      }

      // 更新新闻通知数据
      if (data.newsNotices) {
        newsItems.value = data.newsNotices.newsItems || [];
        notices.value = data.newsNotices.notices || [];
        activeNewsTab.value = data.newsNotices.activeTab || 'notices';
      }

      // 更新日历数据
      if (data.calendar) {
        selectedMonth.value = data.calendar.selectedMonth || '';
        calendarDays.value = data.calendar.calendarDays || [];
      }

    } else {
      ElMessage.error(response.message || '获取侧边栏数据失败');
    }
  } catch (error) {
    console.error('加载侧边栏数据失败:', error);
    ElMessage.error('加载侧边栏数据失败');
  }
};

// 初始化当前月份
onMounted(() => {
  const year = today.value.getFullYear();
  const month = today.value.getMonth() + 1;
  selectedMonth.value = `${year}-${month.toString().padStart(2, '0')}`;

  // 加载数据
  loadSidebarData();
});

// 月份变更处理
const changeMonth = () => {
  console.log('月份变更:', selectedMonth.value);
};

// 处理推荐点击 - 导航到资源详情页
const handleRecommendationClick = (item) => {


  if (!item.type) {
    ElMessage.warning('该资源暂不支持预览');
    return;
  }

  // 路由映射配置
  const routeMap = {
    'pdf': '/student/fileViewerPDF',
    'doc': '/student/fileViewerWord',
    'docx': '/student/fileViewerWord',
    'ppt': '/student/fileViewerPPT',
    'pptx': '/student/fileViewerPPT',
    'xls': '/student/fileViewerExcel',
    'xlsx': '/student/fileViewerExcel',
    'video': '/student/fileViewerVideo',
    'image': '/student/fileViewerImage'
  };

  // 文件路径映射配置
  const filePathMap = {
    'video': '/pdfjs/test.mp4',
    'doc': '/pdfjs/test.docx',
    'docx': '/pdfjs/test.docx',
    'pdf': '/pdfjs/test.pdf',
    'ppt': '/pdfjs/test.pptx',
    'pptx': '/pdfjs/test.pptx',
    'xls': '/pdfjs/test.xlsx',
    'xlsx': '/pdfjs/test.xlsx',
    'image': '/pdfjs/test.jpg'
  };

  const routePath = routeMap[item.type] || '/student/resources';
  const filePath = filePathMap[item.type] || '/pdfjs/test.docx';

  router.push({
    path: routePath,
    query: {
      type: item.type,
      title: item.title,
      id: extractIdFromUrl(item.url),
      fileUrl: filePath
    }
  });
};

// 修改活动点击处理函数 - 显示活动详情弹窗
const handleActivityClick = (activity) => {
  console.log('打开活动:', activity);

  // 从URL中提取活动ID
  const activityId = extractIdFromUrl(activity.url);

  if (activityId) {
    selectedActivityId.value = activityId;
    activityDetailVisible.value = true;
  } else if (activity.id) {
    // 如果活动有直接的id字段
    selectedActivityId.value = activity.id;
    activityDetailVisible.value = true;
  } else {
    ElMessage.info('该活动暂无详细信息');
  }
};

// 处理新闻点击
const handleNewsClick = (news) => {
  console.log('打开新闻:', news.title);

  // 导航到新闻详情页
  router.push({
    path: '/news-detail',
    query: {
      id: news.id,
      title: news.title,
      type: news.type
    }
  });
};

// 处理通知点击 - 直接使用侧边栏返回的完整数据
const handleNoticeClick = async (notice) => {
  console.log('打开通知:', notice);

  try {
    // 从URL中提取通知ID
    const noticeId = notice.noticeId || extractIdFromUrl(notice.url);

    if (!noticeId) {
      ElMessage.error('无法获取通知ID');
      return;
    }

    // 获取用户信息
    const userInfoStr = localStorage.getItem('userInfo');
    const userInfo = userInfoStr ? JSON.parse(userInfoStr) : null;
    const userId = userInfo?.id;

    if (!userId) {
      ElMessage.error('无法获取用户信息，请重新登录');
      return;
    }

    // 直接使用侧边栏返回的完整数据
    currentNotice.value = {
      noticeId: notice.noticeId,
      title: notice.title,
      content: notice.content,
      typeName: notice.typeName,
      senderName: notice.senderName,
      createTime: notice.createTime || notice.time,
      description: notice.description
    };

    noticeDetailVisible.value = true;

    // 标记为已读
    await markNoticeAsRead(parseInt(noticeId), parseInt(userId));

  } catch (error) {
    console.error('打开通知详情失败:', error);
    ElMessage.error('打开通知详情失败');
  }
};

// 关闭通知详情弹窗
const handleCloseNoticeDetail = () => {
  noticeDetailVisible.value = false;
  currentNotice.value = null;
};

// 处理日期点击
const handleDayClick = (day) => {
  if (day.isCurrentMonth) {
    console.log('选择日期:', day.date.toLocaleDateString());

    // 导航到日程详情页
    router.push({
      path: '/schedule-detail',
      query: {
        date: day.date.toISOString().split('T')[0],
        hasEvent: day.hasEvent
      }
    });
  }
};
</script>

<style scoped>
.sidebar-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.module {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  min-height: 200px;
  display: flex;
  flex-direction: column;
}

.module:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.module-header {
  position: relative;
  padding: 16px 20px;
  background: #1e62ec;
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.module-header h2 {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.tabs-container {
  display: flex;
  align-items: center;
}

.month-selector {
  display: flex;
  align-items: center;
  width:120px;
}

/* 选项卡样式 */
:deep(.el-radio-group) {
  margin-left: 10px;
}

:deep(.el-radio-button) {
  --el-radio-button-checked-bg-color: rgba(255, 255, 255, 0.2);
  --el-radio-button-checked-text-color: white;
  --el-radio-button-checked-border-color: transparent;
}

:deep(.el-radio-button__inner) {
  background: rgba(255, 255, 255, 0.1);
  border: none;
  color: rgba(255, 255, 255, 0.8);
  border-radius: 4px;
  padding: 5px 12px;
  font-size: 12px;
  transition: all 0.3s;
}

:deep(.el-radio-button__inner:hover) {
  color: white;
  background: rgba(255, 255, 255, 0.15);
}

:deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-radius: 4px 0 0 4px;
}

:deep(.el-radio-button:last-child .el-radio-button__inner) {
  border-radius: 0 4px 4px 0;
}

/* 月份选择器样式 */
:deep(.el-date-editor) {
  width: 120px;
}

:deep(.el-input__inner) {
  background: rgba(255, 255, 255, 0.1);
  border: none;
  color: white;
  height: 28px;
  line-height: 28px;
  padding: 0 10px;
  border-radius: 4px;
}

:deep(.el-input__prefix) {
  display: none;
}

:deep(.el-input__suffix) {
  right: 5px;
}

:deep(.el-input__suffix .el-icon) {
  color: rgba(255, 255, 255, 0.8);
}

.module-body {
  padding: 15px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

/* 精选推荐样式 */
.recommendation-list, .activity-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.recommendation-item, .activity-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-radius: 8px;
  background: #f9fafc;
  transition: all 0.3s;
  cursor: pointer;
}

.recommendation-item:hover, .activity-item:hover {
  background: #e8f4ff;
  transform: translateY(-2px);
}

.recommendation-icon, .activity-icon {
  width: 36px;
  height: 36px;
  background: #e6f1ff;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  flex-shrink: 0;
}

.recommendation-icon .el-icon, .activity-icon .el-icon {
  font-size: 18px;
  color: #1e62ec;
}

.recommendation-details, .activity-details {
  flex-grow: 1;
  min-width: 0;
}

.recommendation-title, .activity-title {
  font-size: 13px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.recommendation-description {
  font-size: 11px;
  color: #909399;
}

.activity-time {
  font-size: 11px;
  color: #909399;
}

/* 新闻通知样式 */
.news-list, .notices-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.news-item, .notice-item {
  display: flex;
  align-items: flex-start;
  padding: 8px;
  border-radius: 6px;
  background: #f9fafc;
  transition: all 0.3s;
  cursor: pointer;
}

.news-item:hover, .notice-item:hover {
  background: #e8f4ff;
}
.news-badge {
  min-width: 36px;
  padding: 2px 5px;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 500;
  text-align: center;
  margin-right: 8px;
  flex-shrink: 0;
}

.news-badge.important {
  background: #fef0f0;
  color: #f56c6c;
}

.news-badge.normal {
  background: #f0f9eb;
  color: #67c23a;
}

.notice-icon {
  width: 30px;
  height: 30px;
  background: #e6f1ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  flex-shrink: 0;
}

.notice-icon .el-icon {
  font-size: 16px;
  color: #1e62ec;
}

.news-content, .notice-content {
  flex-grow: 1;
}

.news-title, .notice-title {
  font-size: 12px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 2px;
}

.news-time, .notice-time {
  font-size: 10px;
  color: #909399;
}

/* 日历样式 */
.calendar-container {
  display: flex;
  flex-direction: column;
}

.calendar-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  font-size: 12px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 8px;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 4px;
}

.calendar-day {
  aspect-ratio: 1/1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  font-size: 12px;
  cursor: pointer;
  position: relative;
  transition: all 0.2s;
}

.calendar-day.current-month {
  background: #f5f7fa;
  color: #303133;
}

.calendar-day:not(.current-month) {
  background: #fafafa;
  color: #c0c4cc;
}

.calendar-day.today {
  background: #e6f1ff;
  color: #1e62ec;
  font-weight: 600;
}

.calendar-day.has-event::after {
  content: '';
  position: absolute;
  bottom: 3px;
  width: 4px;
  height: 4px;
  border-radius: 50%;
  background: #1e62ec;
}

.calendar-day:hover {
  background: #e8f4ff;
  transform: scale(1.05);
}

.day-number {
  font-size: 13px;
  z-index: 1;
}

.event-indicator {
  position: absolute;
  bottom: 2px;
  width: 4px;
  height: 4px;
  border-radius: 50%;
  background: #1e62ec;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .module-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .tabs-container, .month-selector {
    width: 100%;
    justify-content: flex-end;
  }

  :deep(.el-date-editor) {
    width: 100%;
  }
}

@media (max-width: 992px) {
  .sidebar-container {
    flex-direction: row;
    flex-wrap: wrap;
  }

  .module {
    flex: 1 1 300px;
    min-width: 300px;
  }

  .calendar-day {
    font-size: 11px;
  }
}

@media (max-width: 768px) {
  .module {
    flex: 1 1 100%;
  }

  .recommendation-item, .activity-item {
    padding: 8px;
  }

  .recommendation-icon, .activity-icon {
    width: 32px;
    height: 32px;
    margin-right: 8px;
  }

  .news-item, .notice-item {
    padding: 6px;
  }

  .calendar-header {
    font-size: 11px;
  }

  .calendar-day {
    font-size: 10px;
  }
}

/* 新增自定义月份选择器样式 */
:deep(.custom-month-picker .el-input__inner) {
  background: rgba(255, 255, 255, 0.15) !important;
  border: 1px solid rgba(255, 255, 255, 0.3) !important;
  color: #1e62ec !important;
  height: 28px;
  line-height: 28px;
  padding: 0 10px;
  border-radius: 4px;
  font-size: 12px;
}

:deep(.custom-month-picker .el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.6) !important;
}

:deep(.custom-month-picker .el-input__suffix .el-icon) {
  color: rgba(255, 255, 255, 0.8) !important;
}

:deep(.custom-month-picker .el-input__suffix) {
  right: 5px;
}

/* 下拉面板样式 */
:deep(.el-picker__popper) {
  background: #fff !important;
  border-radius: 8px !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
}

:deep(.el-picker__popper .el-date-picker__header-label) {
  color: #303133 !important;
}

:deep(.el-picker__popper .el-date-table th) {
  color: #606266 !important;
}

:deep(.el-picker__popper .el-date-table td.current:not(.disabled) .el-date-table-cell__text) {
  background-color: #1e62ec !important;
  color: white !important;
}

:deep(.el-picker__popper .el-date-table td .el-date-table-cell__text) {
  color: #606266 !important;
}

:deep(.el-picker__popper .el-date-table td.today .el-date-table-cell__text) {
  color: #1e62ec !important;
  font-weight: bold;
}

/* 响应式调整 */
@media (max-width: 768px) {
  :deep(.custom-month-picker .el-input__inner) {
    width: 100px;
    font-size: 11px;
    padding: 0 8px;
  }
}
</style>
